package com.hhf.springboot.mq;

import com.hhf.springboot.common.ErrorCode;
import com.hhf.springboot.exception.BusinessException;
import com.hhf.springboot.manager.AiManager;
import com.hhf.springboot.model.entity.Chart;
import com.hhf.springboot.model.enums.ChartStatusEnum;
import com.hhf.springboot.service.ChartService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;

/**
 * @Author hhf
 * @Date 2025/6/15
 * @Description
 */
@Component
@Slf4j
public class MyMessageConsumer {

    @Resource
    private ChartService chartService;

    @Resource
    private AiManager aiManager;


    /**
     * 处理死信队列消息
     * @param message
     * @param channel
     * @param deliveryTag
     * @throws IOException
     */
    @RabbitListener(queues = {BiMqConstant.DEAD_QUEUE},ackMode = "MANUAL")
    public void handleDeadLetter(String message, Channel channel,@Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag) throws IOException {
        log.error("接收到死信:{}",message);

        //修改chart状态
        long chartId = Long.parseLong(message);
        Chart updateChart = new Chart();
        updateChart.setId(chartId);
        updateChart.setStatus(ChartStatusEnum.FAILED.getValue());


        //手动确认消息
        channel.basicAck(deliveryTag,false);
    }


    /**
     * 接收消息
     *
     * @param message 消息内容
     * @param channel 消息所在的通道,可以通过channel与RabbitMQ进行交互,比如手动确认消息,拒绝消息等
     * @param deliveryTag 消息标签,用于消息唯一标识
     */
    @RabbitListener(queues = {BiMqConstant.BI_QUEUE},ackMode = "MANUAL")
    public void receiveMessage(String message, Channel channel,@Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag) throws IOException {
        log.info("接收到消息:{}",message);

        if (StringUtils.isBlank(message)){
            channel.basicNack(deliveryTag,false,false);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"message为空");
        }

        //查询chart信息
        Chart chart = chartService.getById(Long.parseLong(message));
        if (ObjectUtils.isEmpty(chart)){
            channel.basicNack(deliveryTag,false,false);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"chart为空");
        }


        // 构造用户输入
        String userInput = buildUserInput(chart);

        //修改图表状态->运行中
        // 先修改图表任务状态为 “执行中”。等执行成功后，修改为 “已完成”、保存执行结果；执行失败后，状态修改为 “失败”，记录任务失败信息。
        Chart updateChart = new Chart();
        updateChart.setId(chart.getId());
        updateChart.setStatus(ChartStatusEnum.RUNNING.getValue());
        boolean updateResult = chartService.updateById(updateChart);
        if (!updateResult) {
            channel.basicNack(deliveryTag,false,false);
            handleChartUpdateError(chart.getId(), "更新图表执行中状态失败");
            return;
        }

        //调用 AI方法
        String result = aiManager.doChat(userInput.toString());
        String[] splits = result.split("【【【【【");
        if (splits.length < 3) {
            channel.basicNack(deliveryTag,false,false);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "AI 生成错误");
        }
        String genChart = splits[1].trim();
        String genResult = splits[2].trim();

        //修改图表状态->完成
        updateChart.setId(chart.getId());
        updateChart.setStatus(ChartStatusEnum.SUCCEED.getValue());
        updateChart.setGenChart(genChart);
        updateChart.setGenResult(genResult);
        updateChart.setExecMessage("执行成功");
        updateResult = chartService.updateById(updateChart);
        if (!updateResult) {
            channel.basicNack(deliveryTag,false,false);
            handleChartUpdateError(chart.getId(), "更新图表成功状态失败");
        }


        //手动确认消息
        channel.basicAck(deliveryTag,false);
    }

    /**
     * 处理图表更新方法
     *
     * @param chartId
     * @param execMessage
     */
    private void handleChartUpdateError(long chartId, String execMessage) {
        Chart updateChartResult = new Chart();
        updateChartResult.setId(chartId);
        updateChartResult.setStatus("failed");
        updateChartResult.setExecMessage(execMessage);
        boolean updateResult = chartService.updateById(updateChartResult);
        if (!updateResult) {
            log.error("更新图表失败状态失败" + chartId + "," + execMessage);
        }
    }

    /**
     * 构建用户输入
     * @param chart 图表对象
     * @return 用户输入字符串
     */
    private String buildUserInput(Chart chart) {
        // 获取图表的目标、类型和数据
        String goal = chart.getGoal();
        String chartType = chart.getChartType();
        String csvData = chart.getChartData();

        // 构造用户输入
        StringBuilder userInput = new StringBuilder();
        userInput.append("分析需求：").append("\n");

        // 拼接分析目标
        String userGoal = goal;
        if (StringUtils.isNotBlank(chartType)) {
            userGoal += "，请使用" + chartType;
        }
        userInput.append(userGoal).append("\n");
        userInput.append("原始数据：").append("\n");
        userInput.append(csvData).append("\n");
        // 将StringBuilder转换为String并返回
        return userInput.toString();
    }


}
